package handlers

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/kataras/iris/v12"
)

var elasticsearchClient *elasticsearch.Client

func init() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://192.168.10.160:9200",
		},
	}
	elasticsearchClient, _ = elasticsearch.NewClient(cfg)
	fmt.Print("1")
}

//
func ElasticHandler(ctx iris.Context) {

	q := ctx.URLParamDefault("q", "")

	if q == "" {
		ctx.JSON(NewJsonMessage().Error().WithMessage("请输入搜索关键词."))
		return
	}

	var buf bytes.Buffer
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"name": q,
			},
		},
	}

	json.NewEncoder(&buf).Encode(query)

	resp, err := elasticsearchClient.Search(
		elasticsearchClient.Search.WithContext(context.Background()),
		elasticsearchClient.Search.WithBody(&buf),
		elasticsearchClient.Search.WithPretty(),
	)

	defer resp.Body.Close()

	if err != nil {
		ctx.JSON(NewJsonMessage().Error().WithMessage("搜索异常."))
		return
	}

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)

	ohits, _ := result["hits"].(map[string]interface{})
	hits, _ := ohits["hits"].([]interface{})

	var data []map[string]interface{}

	for _, each := range hits {
		hit, _ := each.(map[string]interface{})

		source := hit["_source"].(map[string]interface{})

		data = append(data, map[string]interface{}{
			"_id_":   hit["_id"],
			"_index": hit["_index"],
			"name":   source["name"],
		})
	}

	ctx.JSON(NewJsonMessage().Success().WithData(data))
}
